<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="业主名称">
            <j-popup
                v-model="queryParam.ownerCode"
                org-fields="owner_code,owner_name,owner_type,owner_trade,id_card"
                dest-fields="ownerCode,ownerName,ownerType,ownerTrade,idCard"
                field="ownerCode"
                code="v_xy_park_owner"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="结清状态">
              <j-dict-select-tag
                :disabled="disableSubmit"
                v-model="queryParam.clearStatus"
                placeholder="请选择结清状态"
                dict-code="xy_park_bill_clear"
              >
              </j-dict-select-tag>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="应收/付日期" style="width:100%;">
                <j-date placeholder="开始日期" v-model="queryParam['dueDate_begin']" style="width:calc(50% - 15px);"></j-date>
                <span class="group-query-strig">~</span>
                <j-date placeholder="结束日期" v-model="queryParam['dueDate_end']" style="width:calc(50% - 15px);"></j-date>
              </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="账单来源">
                <j-dict-select-tag v-model="queryParam.billSource"  placeholder="请选择账单来源" dict-code="xy_park_bill_source"></j-dict-select-tag>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="费项名称">
                <j-popup
                  v-model="queryParam.costType"
                  org-fields="cost_type,cost_name,tax_rate"
                  dest-fields="costType,costName,taxRate"
                  field="costType"
                  code="v_xy_park_cost_type"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="账单类型" style="width:100%;">
                <j-dict-select-tag v-model="queryParam.billType"  placeholder="请选择账单类型" dict-code="xy_park_bill_type"></j-dict-select-tag>
              </a-form-item>
            </a-col>
            <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="开始日期" >
                <j-date placeholder="开始日期" v-model="queryParam['startDate']" style="width:100%;" ></j-date>
              </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
              <a-form-item label="结束日期">
                <j-date placeholder="开始日期" v-model="queryParam['endDate']" style="width:100%;" ></j-date>
              </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="合同编号">
              <a-input placeholder="合同编号" v-model="queryParam['contractCode']" style="width:100%;" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="6" :sm="24">
            <a-form-item label="账单编码">
              <a-input placeholder="账单编码" v-model="queryParam['billCode']" style="width:100%;" />
            </a-form-item>
          </a-col>
          </template>
          <a-col :xl="6" :lg="6" :md="6" :sm="24" >
            <span class="table-page-search-submitButtons">
              <a-button type="primary" icon="search" @click="searchQuery">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
      <vxe-grid
        id="BillList"
        keep-source
        ref="vxeTable"
        :height="null"
        v-bind="options"
        :expand-config="{accordion: true}"
        :columns="columns"
        :data="dataSource"
        :sort-config="{trigger:'cell',remote:true}"
        :edit-config="{trigger: 'click', mode: 'row',showStatus: true}"
        @checkbox-change="onSelectChange"
        @checkbox-all="onSelectChange"
        @sort-change="onSortChange"
        @cell-dblclick="handleCellHblclick"
      >
      <template v-slot:toolbar_buttons>
        <div class="table-operator">
          <a-dropdown>
            <a-menu slot="overlay">
              <a-menu-item key="1" @click="handleAdd('1')" icon="plus">新增收款</a-menu-item>
              <a-menu-item key="2" @click="handleAdd('2')" icon="plus">新增付款</a-menu-item>
            </a-menu>
            <a-button type="primary" icon="plus" >新增</a-button>
          </a-dropdown>
          <!-- <a-button style="margin-left:5px;" ghost type="primary" icon="import" @click="handleSub">提交</a-button>
          <a-button v-has="'BillList:check'" style="margin-left:5px;" ghost type="primary" icon="check-square" @click="handleCheck">审批</a-button>
          <a-button v-has="'BillList:reject'" style="margin-left:5px;" ghost type="danger" icon="check-square" @click="handleReject">驳回</a-button>
          <a-button v-has="'BillList:close'" style="margin-left:5px;" ghost type="danger" icon="close" @click="handleClose">关闭</a-button> -->
        </div>
      </template>
      <template v-slot:toolbar_tools>
        <vxe-button style="margin-right:12px;" @click="handleExportXls('账单列表')" icon="vxe-icon--download" circle></vxe-button>
        <!-- <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
          <vxe-button style="margin-right:12px;" icon="vxe-icon--upload" circle />
        </a-upload> -->
      </template>
      <template #action="{ row }">
        <template>
          <a v-if="row.billStatus === '1'" @click="handleEdit(row)">编辑</a>
          <a-divider type="vertical" v-if="row.billStatus === '1'" />
          <a @click="handleSub(row)" v-if="row.billStatus === '1'">提交</a>
          <a-divider type="vertical" v-if="row.billStatus === '1'" />
          <a @click="handleCheck(row)" v-has="'BillList:check'" v-if="row.billStatus === '2'">通过</a>
          <a-divider type="vertical" v-has="'BillList:check'" v-if="row.billStatus === '2'" />
          <a @click="handleReject(row)" v-has="'BillList:reject'" v-if="(row.billStatus === '2' || row.billStatus === '3') && !row.checkAmount">驳回</a>
          <a-divider type="vertical" v-has="'BillList:reject'" v-if="row.billStatus === '2' || row.billStatus === '3'" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多<a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(row)">详情</a>
              </a-menu-item>
              <a-menu-item v-has="'BillList:close'" v-if="row.billStatus === '3'">
                <a @click="handleClose(row)">关闭</a>
              </a-menu-item>
              <a-menu-item v-if="row.billStatus === '1'">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(row.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </template>
      <template v-slot:pager>
        <vxe-pager
          :layouts="['Sizes', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          :current-page.sync="ipagination.currentPage"
          :page-size.sync="ipagination.pageSize"
          :total="ipagination.total"
          @page-change="handlePageChange"
        >
        </vxe-pager>
      </template>
    </vxe-grid>
    <BillListModal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

import { VxeTableMixin } from '@/mixins/VxeTableMixin'
import BillListModal from './modules/BillListModal'
import { filterDictTextByCache } from '@/components/dict/JDictSelectUtil'
import { getAction } from '@/api/manage'
import moment from 'moment'
import JDate from '@/components/jeecg/JDate'
export default {
  name: 'BillList',
  mixins: [VxeTableMixin],
  components: {
    BillListModal,
    JDate
  },
  data() {
    return {
      isorter: {
        column: 'billCode',
        order: 'desc'
      },
      columns: [
        { type: 'checkbox', width: 40 },
        { type: 'seq', width: 40 },
        { title: '账单编码', field: 'billCode', width: 80, showOverflow: true },
        { title: '账单类型', field: 'billType', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          return filterDictTextByCache('xy_park_bill_type', row.billType)
        } }},
        { title: '账单金额', field: 'amount', width: 80, showOverflow: true },
        { title: '应收/付日期', field: 'dueDate', width: 120, showOverflow: true, sortable: true },
        { title: '业主名称', field: 'xyParkOwner.ownerName', width: 120, showOverflow: true },
        { title: '合同/协议编码', field: 'contractCode', width: 100, showOverflow: true },
        // { title: '合同/协议类型', field: 'contractCode', width: 100, showOverflow: true },
        { title: '账单来源', field: 'billSource', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          return filterDictTextByCache('xy_park_bill_source', row.billSource)
        } }},
        { title: '账单状态', field: 'billStatus', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          return filterDictTextByCache('xy_park_bill_status', row.billStatus)
        } }},
        { title: '结清状态', field: 'clearStatus', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          return filterDictTextByCache('xy_park_bill_clear', row.clearStatus)
        } }},
        { title: '费项名称', field: 'xyParkCostType.costName', width: 80, showOverflow: true },
        { title: '开始日期', field: 'startDate', width: 80, showOverflow: true },
        { title: '结束日期', field: 'endDate', width: 80, showOverflow: true },

        { title: '税率', field: 'xyParkCostType.taxRate', width: 80, showOverflow: true },
        { title: '应收不含税', field: 'importanceScore', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          const amount = row.amount
          return amount - this.getTaxAmount(row)
        } }},
        { title: '应收税额', field: 'forecastTime', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          return this.getTaxAmount(row)
        } }},
        { title: '已勾稽金额', field: 'checkAmount', width: 80, showOverflow: true },
        { title: '未勾稽金额', field: 'a', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          const amount = row.amount
          return amount - (row.checkAmount || 0)
        } }},
        { title: '逾期天数', field: 'overdueDays', width: 80, showOverflow: true, slots: { default: ({ row }) => {
          const overdueDays = moment().diff(row.dueDate, 'days')
          if (overdueDays > 0 && row.clearStatus !== '3') {
            return overdueDays
          } else {
            return ''
          }
        } }},
        { title: '操作', width: 150, field: 'action', fixed: 'right', slots: { default: 'action' }}
      ],
      url: {
        list: '/community/bill/list',
        delete: '/community/bill/delete',
        deleteBatch: '/community/bill/deleteBatch',
        approvalBatch: '/community/bill/approvalBatch',
        exportXlsUrl: '/community/bill/export',
        importExcelUrl: 'community/bill/importExcel'
      },
      disableMixinCreated: true,
      innerTableWidth: 600
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    handleEdit: function(record) {
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.edit(record)
    },
    handleAdd: function(type) {
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.add(type)
    },
    handleCheck(row) {
      if (row.billStatus === '2') {
        this.approvalBatch('3', row)
      } else {
        this.$message.warning('只能选择审批中状态的账单')
      }
      // if (this.selectionRows.length) {
      //   let flag = false
      //   this.selectionRows.forEach(item => {
      //     if (item.billStatus !== '2') {
      //       flag = true
      //       return false
      //     }
      //   })
      //   if (flag) {
      //     return this.$message.warning('只能选择审批中状态的账单')
      //   }
      //   this.approvalBatch('3')
      // } else {
      //   this.$message.warning('请选择需要审批的账单')
      // }
    },
    handleSub(row) {
      if (row.billStatus === '1') {
        this.approvalBatch('2', row)
      } else {
        this.$message.warning('只能选择未审批状态的账单')
      }
      // if (this.selectionRows.length) {
      //   let flag = false
      //   this.selectionRows.forEach(item => {
      //     if (item.billStatus !== '1') {
      //       flag = true
      //       return false
      //     }
      //   })
      //   if (flag) {
      //     return this.$message.warning('只能选择未审批状态的账单')
      //   }
      //   this.approvalBatch('2')
      // } else {
      //   this.$message.warning('请选择需要提交审批的账单')
      // }
    },
    handleReject(row) {
      if (row.billStatus === '2' || row.billStatus === '3') {
        this.approvalBatch('1', row)
      } else {
        this.$message.warning('只能选择审批中状态的账单')
      }
      // if (this.selectionRows.length) {
      //   let flag = false
      //   this.selectionRows.forEach(item => {
      //     if (item.billStatus !== '2') {
      //       flag = true
      //       return false
      //     }
      //   })
      //   if (flag) {
      //     return this.$message.warning('只能选择审批中状态的账单')
      //   }
      //   this.approvalBatch('1')
      // } else {
      //   this.$message.warning('请选择需要驳回的账单')
      // }
    },
    handleClose(row) {
      if (row.billStatus === '3') {
        this.approvalBatch('4', row)
      } else {
        this.$message.warning('只能关闭已审批状态的账单')
      }
      // if (this.selectionRows.length) {
      //   let flag = false
      //   this.selectionRows.forEach(item => {
      //     if (item.billStatus !== '3') {
      //       flag = true
      //       return false
      //     }
      //   })
      //   if (flag) {
      //     return this.$message.warning('只能关闭已审批状态的账单')
      //   }
      //   this.approvalBatch('4')
      // } else {
      //   this.$message.warning('请选择需要关闭的账单')
      // }
    },
    approvalBatch(status, row) {
      getAction(this.url.approvalBatch, { ids: row.id, status: status }).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.loadData()
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getTaxAmount(row) {
      const taxRate = row.xyParkCostType ? row.xyParkCostType.taxRate : 0
      const amount = row.amount
      let taxAmount
      if (taxRate && amount) {
        taxAmount = (amount * taxRate) / 100
      } else {
        taxAmount = 0
      }
      return taxAmount.toFixed(2)
    }
  },
  created() {
    this.loadData(1)
  },
  mounted() {
    this.$nextTick(() => {
      const columns = this.$refs.vxeTable.getColumnByField('action')
      const tableWidth = this.$refs.vxeTable.$el.clientWidth
      this.innerTableWidth = (tableWidth - columns.width - 30) + 'px'
    })
  }
}
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
